<?php

namespace mszl\api\utils;

use Exception;
use mszl\api\traits\DynamicParamsSingleton;

class IniReader
{
    use DynamicParamsSingleton;

    private array $config = [];

    /**
     * @throws Exception
     */
    public function __construct($file, $section = '')
    {
        $path = env('DB_INI_PATH', '../');
        $fullName = $path . $file . ".ini";

        if (file_exists($fullName)) {
            $this->config = parse_ini_file($fullName, true);
            if ($section !== '') {
                $this->config = $this->config[$section] ?? [];
            }
        } else {
            throw new Exception("配置文件[$file]不存在");
        }
    }

    public function get($key = null, $default = null): mixed
    {
        return $key ? ($this->config[$key] ?? $default) : $this->config;
    }
}